package com.feishi.project.broker.filter;

import com.feishi.core.analytic.assembler.BaseAssembler;
import com.feishi.core.analytic.assembler.DefaultAssembler;
import com.feishi.core.socket.common.filter.SocketFilter;
import com.feishi.core.socket.common.lifecycle.SocketRequest;
import com.feishi.core.util.common.ByteUtil;
import lombok.extern.log4j.Log4j;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: caixq
 * Date: 2018-12-25
 * Time: 上午10:22
 */
@Slf4j
@Component
public class BrokerFilter<T extends DefaultAssembler> implements SocketFilter<T> {

    @Value("${mqtt.port}")
    private int port;
    @Value("${mqtt.host}")
    private String host;
    @Override
    public boolean doFilter(SocketRequest request, T defaultAssembler) {


        Socket client = (Socket) request.getSession().getAttribute("client");
        if (client == null) {
            try {
                client = new Socket(host, port);
                OutputStream outputStream = client.getOutputStream();
                request.getSession().setAttribute("client", client);
                InputStream ins = client.getInputStream();
                new Thread(() -> {
                    try {

                        while (true) {
                            if (ins.available() > 0) {
                                byte[] bs = new byte[ins.available()];

                                ins.read(bs);
                                log.info("msg from server::" + ByteUtil.getHexString(defaultAssembler.getContent()));
                                request.getSession().write(bs);
                            }

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }).start();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

        try {
            log.info("msg from client::" + ByteUtil.getHexString(defaultAssembler.getContent()));
            client.getOutputStream().write(defaultAssembler.getContent());
            client.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


}
